package com.lab.web.controller.biz;

import com.lab.common.annotation.Log;
import com.lab.common.core.controller.BaseController;
import com.lab.common.core.domain.AjaxResult;
import com.lab.common.core.domain.model.LoginUser;
import com.lab.common.core.page.TableDataInfo;
import com.lab.common.enums.BusinessType;
import com.lab.common.utils.poi.ExcelUtil;
import com.lab.system.domain.ExperimentCourse;
import com.lab.system.domain.Reservations;
import com.lab.system.service.IExperimentCourseService;
import com.lab.system.service.IReservationsService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 实验预约Controller
 *
 * @author cf
 * @date 2025-02-10
 */
@RestController
@RequestMapping("/biz/reservation")
public class ReservationsController extends BaseController {
    @Autowired
    private IReservationsService reservationsService;
    @Autowired
    private IExperimentCourseService courseService;

    /**
     * 查询实验预约列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Reservations reservations) {
        startPage();
        LoginUser loginUser = getLoginUser();
        List<Reservations> list = reservationsService.selectReservationsList(reservations,loginUser);
        return getDataTable(list);
    }

    /**
     * 查询实验预约列表
     */
    @GetMapping("/list/me")
    public TableDataInfo listMe(Reservations reservations) {
        startPage();
        reservations.setUserId(getUserId());
        List<Reservations> list = reservationsService.selectReservationsList(reservations,getLoginUser());
        return getDataTable(list);
    }

    /**
     * 查询当前用户的预约记录
     */
    @GetMapping("/listByCurrentUser")
    public TableDataInfo listByCurrentUser(Reservations reservations) {
        startPage();
        List<Reservations> list = reservationsService.selectReservationsListByUser(reservations, getUserId());
        return getDataTable(list);
    }

    /**
     * 导出实验预约列表
     */
    @Log(title = "实验预约", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Reservations reservations) {
        List<Reservations> list = reservationsService.selectReservationsList(reservations,getLoginUser());
        ExcelUtil<Reservations> util = new ExcelUtil<Reservations>(Reservations.class);
        util.exportExcel(response, list, "实验预约数据");
    }

    /**
     * 获取实验预约详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(reservationsService.selectReservationsById(id));
    }

    /**
     * 新增实验预约
     */
    @Log(title = "实验预约", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Reservations reservations) {
        if (reservations.getUserId() == null) {
            reservations.setUserId(getUserId());
        }

        List<Reservations> reservationsList = reservationsService.selectReservationsList(reservations, null);
        if (CollectionUtils.isNotEmpty(reservationsList)) {
            return error("您已经预约过该课程");
        }

        // 查询课程
        ExperimentCourse experimentCourse = courseService.selectExperimentCourseById(reservations.getCourseId());

        // 查询实验室甚于容纳人数
        Integer remainCapacity = courseService.getRemainCapacity(experimentCourse);
        if (remainCapacity == null || remainCapacity < 0) {
            return error("当前实验室容纳人数不足");
        }

        return toAjax(reservationsService.insertReservations(reservations));
    }

    /**
     * 修改实验预约
     */
    @Log(title = "实验预约", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Reservations reservations) {
        return toAjax(reservationsService.updateReservations(reservations));
    }

    /**
     * 删除实验预约
     */
    @Log(title = "实验预约", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(reservationsService.deleteReservationsByIds(ids));
    }

    /**
     * 取消预约
     */
    @Log(title = "实验预约", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{id}")
    public AjaxResult cancel(@PathVariable Long id) {
        Long userId = getUserId();
        Reservations reservations = reservationsService.selectReservationsById(id);
        if (reservations == null) {
            return error("预约不存在");
        }
        if (!reservations.getUserId().equals(userId)) {
            return error("您没有权限取消该预约");
        }
        if(reservations.getStatus() != 1L) {
            return error("当前状态不支持取消预约");
        }
        reservations.setStatus(2L);
        return toAjax(reservationsService.updateReservations(reservations));
    }

    /**
     * 审核预约
     */
    @Log(title = "实验预约", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestParam("id") Long id, @RequestParam("audit") Integer audit) {
        Reservations reservations = reservationsService.selectReservationsById(id);
        if (reservations == null) {
            return error("预约不存在");
        }
        if (reservations.getStatus() != 0L) {
            return error("当前状态不支持审核预约");
        }
        // 判断audit,当audit已经审批完成不允许审批
        if(reservations.getAudit() == 2 || reservations.getAudit() == 3) {
            return error("当前状态已经审批完成");
        }
        // 判断audit,当audit已经审批完成不允许审批
        if(reservations.getAudit() == 1 && audit == 1) {
            return error("已经完成一级审批，无需重复审批");
        }
        reservations.setAudit(audit);
        return toAjax(reservationsService.updateReservations(reservations));
    }
}
